package com.pangus.toolkits.files.download;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.pangus.toolkits.files.http.Response;
import com.pangus.toolkits.files.model.FileInfo;
import com.pangus.toolkits.files.operation.FSFileOperation;
import com.pangus.toolkits.files.request.Range;
import com.pangus.toolkits.files.utils.ResponseUtil;
import okhttp3.ResponseBody;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;

/**
 * @author yingheng chen
 * @description
 * @date 2019/12/5
 */
public class SimpleDownload implements DownloadStrategy {
    private final FileInfo fileInfo;
    private final FSFileOperation fileOperation;

    public SimpleDownload(FileInfo fileInfo, FSFileOperation fileOperation) {
        this.fileInfo = fileInfo;
        this.fileOperation = fileOperation;
    }

    @Override
    public File download(@Nonnull File parent, String filename) throws IOException {

        final Response<ResponseBody> response = fileOperation.downLoad(fileInfo, Range.ALL);
        if (StrUtil.isBlank(filename)) {
            filename = ResponseUtil.getFileNameFromDisposition(response.getHeaders());
            if (StrUtil.isBlank(filename)) {
                filename = UUID.fastUUID().toString().replace("-", "");
            }
        }
        final File file = FileUtil.file(parent, filename);
        try (ResponseBody data = response.getData()) {
            IoUtil.copy(data.byteStream(), FileUtil.getOutputStream(file));
        }
        return file;
    }
}
